<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.code" placeholder="字典code(请输入完整code)" class="filter-item" style="width: 210px;" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button> -->
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate"
        >
        添加
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="handlePlDelete"
        >
        批量删除
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="手机号" prop="mobile" align="center" />
      <!-- <el-table-column label="编号" prop="identifier" align="center" /> -->
      <el-table-column label="省市区" align="center">
        <template slot-scope="{row}">
          <span>{{ row.provinceName }}/{{ row.cityName }}/{{ row.districtName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="address" align="center" />
      <el-table-column label="是否默认" align="center">
        <template slot-scope="{row}">
          {{row.isDefault === 1 ? '是' : '否'}}
          <!-- <el-switch @change="()=>handleSetDefault(row)" :value="row.isDefault === 1">
          </el-switch> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230px">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" >
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleSetDefault(row)" v-if="row.isDefault !== 1">
            设为默认地址
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" />
        </el-form-item>
        <!-- <el-form-item label="编号">
          <el-input v-model="temp.identifier" />
        </el-form-item> -->
        <el-form-item label="省市区" prop="city">
          <AddressCascader ref="addressCascader" v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-radio-group v-model="temp.isDefault">
            <el-radio v-for="item in isDefaultJson" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addressPageByQo, addressSetDefault, addressSaveOrUpdate, addressRemoveByIds } from '@/api/company'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AddressCascader from '@/components/AddressCascader'

export default {
  name: 'Address',
  directives: { waves },
  components: { AddressCascader, Pagination },
  data() {
    const validateCity = (rule, value, callback) => {
      if (!this.temp.districtId) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20
      },
      temp: {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑地址',
        create: '添加地址'
      },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        mobile: [{ required: true, validator: this.$mobileValidator, trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        city: [{ required: true, trigger: 'blur', validator: validateCity }]
      },
      multipleSelection: [],
      selectedOptions: [],
      isDefaultJson: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      addressPageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: 0,
        name: '',
        mobile: '',
        identifier: '',
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        districtId: '',
        districtName: '',
        address: '',
        isDefault: 0
      }
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.temp, `provinceId`, value.provinceId)
        this.$set(this.temp, `provinceName`, value.provinceName)
        this.$set(this.temp, `cityId`, value.cityId)
        this.$set(this.temp, `cityName`, value.cityName)
        this.$set(this.temp, `districtId`, value.districtId)
        this.$set(this.temp, `districtName`, value.districtName)
      } else {
        this.$set(this.temp, `provinceId`, '')
        this.$set(this.temp, `provinceName`, '')
        this.$set(this.temp, `cityId`, '')
        this.$set(this.temp, `cityName`, '')
        this.$set(this.temp, `districtId`, '')
        this.$set(this.temp, `districtName`, '')
      }
    },
    handleCreate() {
      this.resetTemp()
      this.selectedOptions = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      if (this.temp.districtId) {
        this.selectedOptions = [this.temp.provinceId.toString(), this.temp.cityId.toString(), this.temp.districtId.toString()]
      } else {
        this.selectedOptions = []
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.createTime
          addressSaveOrUpdate(this.temp, this.dialogStatus !== 'create').then(() => {
            this.getList()
            this.dialogFormVisible = false
            // this.$notify({
            //   title: '成功',
            //   message: '保存成功',
            //   type: 'success',
            //   duration: 2000
            // })
            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    handleSetDefault(row) {
      addressSetDefault({ id: row.id }).then(() => {
        // this.$notify({
        //   title: '成功',
        //   message: '设置成功！',
        //   type: 'success',
        //   duration: 2000
        // })

        this.$message({
          message: '设置成功！',
          type: 'success'
        });
        this.getList()
      })
    },
    // 批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val.map((ele) => {
        return ele.id
      })
    },
    handlePlDelete() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续删除？').then(() => {
        addressRemoveByIds(params).then(() => {
          // this.$notify({
          //   title: '成功',
          //   message: '批量删除成功！',
          //   type: 'success',
          //   duration: 2000
          // })

          this.$message({
            message: '批量删除成功！',
            type: 'success'
          });
          this.getList()
        })
      })
    }
  }
}
</script>
